package com.shy.base.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.shy.base.util.HttpServletRequestResover;
import com.shy.base.vo.AppConstants;
import com.shy.base.vo.EasyuiResult;
import com.shy.base.vo.PagerFilter;

/**
 * 处理分页、响应增、删、改结果json 、处理页面data转换
 * 
 * @author H2013788
 * @date 2016-8-23
 */
public class AbsController extends BaseController {
	
	
	/**
	 * 常规gson对象
	 */
	protected Gson gson = new Gson();

	/**
	 * 只序列化@Expose注解的属性
	 */
	protected Gson gsonExpose = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

	/**
	 * 格式化日期输出
	 */
	protected Gson gsonDate = new GsonBuilder()
			.setDateFormat(AppConstants.DEFAULT_DATE_FORMAT).create();

	/**
	 * 格式化日期+时间输出
	 */
	protected Gson gsonDateTime = new GsonBuilder()
			.setDateFormat(AppConstants.DEFAULT_DATETIME_FORMAT).create();
	
	/**
	 * 格式化日期+时间输出
	 */
	protected Gson gsonDateTimeSS = new GsonBuilder()
			.setDateFormat(AppConstants.DEFAULT_DATETIMESS_FORMAT).create();

	/**
	 * 格式化日期且只@Expose
	 */
	protected Gson gsonDateExpose = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
			.setDateFormat(AppConstants.DEFAULT_DATE_FORMAT).create();

	/**
	 * 格式化日期时间且只@Expose
	 */
	protected Gson gsonDateTimeExpose = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
			.setDateFormat(AppConstants.DEFAULT_DATETIME_FORMAT).create();
	
	/**
	 * 格式化日期时间且只@Expose
	 */
	protected Gson gsonDateTimeSSExpose = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
			.setDateFormat(AppConstants.DEFAULT_DATETIMESS_FORMAT).create();
	

    /**
     *  页码请求参数名
     */
    private final String pageParamName = "page";
    
    /**
     *  每页显示条数参数名
     */
    private final String rowsParamName = "rows";
    
    /**
     * 排序字段参数名
     */
    private final String orderFieldParamName = "orderField";
    
    /**
     * 排序方式参数名
     */
    private final String orderDirectionParamName = "orderDirection";

	// 后台分页通用方法
	protected PagerFilter getPageable(String orderFilter, String orderDirection) {
		HttpServletRequest request = getRequest();
		HttpServletRequestResover resover = new HttpServletRequestResover(
				request);
		Long pageNum = resover.getLong(pageParamName, 1);
		Long showNum = resover.getLong(rowsParamName, 20);
		String qorder = resover.getString(orderFieldParamName);
		String qorderDriction = resover.getString(orderDirectionParamName);
		orderFilter = (qorder == null || qorder.equals("")) ? orderFilter
				: qorder;
		orderDirection = (qorderDriction == null || qorderDriction.equals("")) ? orderDirection
				: qorderDriction;
		PagerFilter page = new PagerFilter(pageNum, showNum, orderFilter,
				orderDirection);
		return page;
	}

	// 后台分页通用方法
	protected PagerFilter getPageable() {
		HttpServletRequest request = getRequest();
		HttpServletRequestResover resover = new HttpServletRequestResover(
				request);
		Long pageNum = resover.getLong(pageParamName, 1);
		Long showNum = resover.getLong(rowsParamName, 20);
		String order = resover.getString(orderFieldParamName);
        String orderDriction = resover.getString(orderDirectionParamName);
		PagerFilter page = new PagerFilter(pageNum, showNum, order,
				orderDriction);
		return page;
	}

	// 分页前台设置显示页数
	protected PagerFilter getPageable(Long showNum, String orderFilter,
			String orderDirection) {
		Long pageNum = 1L;
		HttpServletRequest request = getRequest();
		if (null != request) {
			HttpServletRequestResover resover = new HttpServletRequestResover(
					request);
			pageNum = resover.getLong(pageParamName, 1);
		}
		PagerFilter page = new PagerFilter(pageNum, showNum, orderFilter,
				orderDirection);
		return page;
	}

	protected PagerFilter getPageable(Long showNum) {
		return getPageable(showNum, "", "");
	}

	// 分页默认显示10条
	protected PagerFilter getPageable10(String orderFilter,
			String orderDirection) {
		HttpServletRequest request = getRequest();
		HttpServletRequestResover resover = new HttpServletRequestResover(
				request);
		Long size = resover.getLong(rowsParamName, 10);
		Long pageNum = resover.getLong(pageParamName, 1);
		PagerFilter page = new PagerFilter(pageNum, size, orderFilter,
				orderDirection);
		return page;
	}

	protected PagerFilter getPageable10() {
		return getPageable10("", "");
	}

	// 分页默认显示20条
	protected PagerFilter getPageable20(String orderFilter,
			String orderDirection) {
		HttpServletRequest request = getRequest();
		HttpServletRequestResover resover = new HttpServletRequestResover(
				request);
		Long size = resover.getLong(rowsParamName, 20);
		Long pageNum = resover.getLong(pageParamName, 1);
		PagerFilter page = new PagerFilter(pageNum, size, orderFilter,
				orderDirection);
		return page;
	}

	protected PagerFilter getPageable20() {
		return getPageable20("", "");
	}

	// 不分页
	protected PagerFilter getPageableByNoPage() {
		PagerFilter page = new PagerFilter(0L, -1L, "", "");
		page.setStart(-1L);
		return page;
	}

	/**
	 * 中文乱码 requestParamer
	 * 
	 * @param strInfo
	 * @return
	 */
	public String toStringUtf8(String strInfo) {
		try {
			String str = new String(getRequest().getParameter(strInfo)
					.getBytes("ISO-8859-1"), "UTF-8");
			return str;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			writePrintStackTrace(e);
		}
		return "";
	}

	protected PagerFilter getPagerFilter() {
		PagerFilter pageFilter = new PagerFilter();
		return pageFilter;
	}

	/**
	 * 上传文件，保留原文件名，回map信息，{'name':'新文件名','path','文件路径','size':'大小'}
	 * 
	 * @param fileDoc
	 * @param path
	 * @return
	 */
	public Map<String, String> uploadFileKeepOriginalNameMap(
			MultipartFile fileDoc, String path) {
		Map<String, String> map = new HashMap<String, String>();
		if (fileDoc != null) {
			String fileName = super.upLoadFileKeepOrginalName(fileDoc,
					AppConstants.configMap.get("fileupload") + "/" + path);
			long fileSize = fileDoc.getSize();
			long fileKb = fileSize / 1024;
			map.put("name", fileDoc.getOriginalFilename());
			map.put("path", path.replaceAll("\\\\", "/") + "/" + fileName);
			map.put("size", fileKb + "KB");
		}
		return map;
	}

	/**
	 * 图片上传,uuid重命名，返回map信息，{'name':'新文件名','path','文件路径','size':'大小'}
	 * 
	 * @param fileDoc
	 * @param path
	 * @return
	 */
	public Map<String, String> uploadFileMap(MultipartFile fileDoc, String path) {
		Map<String, String> map = new HashMap<String, String>();
		if (fileDoc != null) {
			String newFileName = super.upLoadFile(fileDoc, path);
			long fileSize = fileDoc.getSize();
			long fileKb = fileSize / 1024;
			map.put("name", fileDoc.getOriginalFilename());
			map.put("path", path.replaceAll("\\\\", "/") + "/" + newFileName);
			map.put("size", fileKb + "KB");
		}
		return map;
	}

	// ////////////////// 文件上传 end /////////////////////////////


	/**
	 * 写到Response中返回页面
	 * 
	 * @param stringBuffer
	 */
	public void writeResponse(StringBuffer stringBuffer,
            HttpServletResponse response) {
		try {
			//getResponse().setContentType("application/json;charset=utf-8");
			//getResponse().setContentType("text/json;charset=utf-8"); //IE下  json提示下載
		    response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.write(stringBuffer.toString());
			out.flush();
			out.close();

		} catch (IOException e) {
			e.printStackTrace();
			writePrintStackTrace(e);
		}
	}


	/**
	 * 输出json
	 * 
	 * @param object
	 * @author H2013788
	 * @date 2017/9/29下午2:21:29
	 */
	public void writeJson(Object object, HttpServletResponse response) {
		Gson gson = new Gson();
		writeResponse(new StringBuffer(gsonDateTime.toJson(object)), response);
	}

	/**
	 * easyui 返回success結果
	 * 
	 * @param success
	 * @param message
	 * @author H2013788
	 * @date 2017/9/29下午3:45:30
	 */
	public void respEasyuiSuccessResult(String message, HttpServletResponse response) {
		writeJson(EasyuiResult.CreateEasyuiSuccessResult(message), response);
	}

	/**
	 * easyui 返回error結果
	 * 
	 * @param success
	 * @param message
	 * @author H2013788
	 * @date 2017/9/29下午3:45:30
	 */
	public void respEasyuiErrorResult(String message, HttpServletResponse response) {
		writeJson(EasyuiResult.CreateEasyuiErrorResult(message), response);
	}


}
